﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using KsWare.Breconium.Core;
using Ksx.KoCTool.Data;

namespace Ksx.KoCTool.Tabs.AjaxTest {
	/// <summary>
	/// Interaction logic for AjaxTest.xaml
	/// </summary>
	public partial class AjaxTest : UserControl {
		public AjaxTest() {
			InitializeComponent();
		}

		private void ExecuteButtonClick(object sender, RoutedEventArgs e) {
			try {
				string url = mUrlComboBox.Text;
				var parameters = ParseParameterInput(mParameterTextBox.Text);
				if (string.IsNullOrWhiteSpace(url)) {
					mResultTextBox.Text = parameters.ToString();
				} else {
					string result = Execute(url, parameters);
					mResultTextBox.Text = result;
				}
//			} catch(Exception ex) {
//				MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
			} finally {}
		}

		private TestAjaxRequestParameters ParseParameterInput(string text) {
			var lines=text.Split(new []{"\r\n","\r","\n"},StringSplitOptions.RemoveEmptyEntries);
			var dic = new TestAjaxRequestParameters();
			foreach (var line in lines) {
				var namevalue=line.Split(new[] {":", "=", "\t"}, 2, StringSplitOptions.None);
				var name = namevalue[0].Trim();
				var value = namevalue[1].Trim();
				if((value.StartsWith("{") && value.EndsWith("}")) || (value.StartsWith("[") && value.EndsWith("]"))) {
					value = Json.ToJsonObject(value).ToString();
				} else if((value.StartsWith("\"") && value.EndsWith("\""))) {
					value = value.Substring(1,value.Length-2);
				} else {
					
				}
				dic.Add(name,value);
			}
			return dic;
		}

		private string Execute(string url, IAjaxRequestParameters parameters) { 
			var ajax = new AjaxRequestData {
				method     = "post",
				url        = url,
				parameters = parameters
			};
			var cmd = new Command("ajaxrequest", ajax);

			try {((App)Application.Current).Server.DefaultSession.ExecuteCommand(cmd,TimeSpan.FromSeconds(30));} 
			catch (Exception ex) {
				return ex.ToString();//ex.GetType().Name + "\r\n"+ ex.Message);
			}
			return cmd.Result.ToString();
		}

		private void CancelButtonClick(object sender, RoutedEventArgs e) {
			
		}
	}

	class TestAjaxRequestParameters:Dictionary<string,object>,IAjaxRequestParameters {

		public override string ToString() {
			var s = new StringBuilder();
			foreach (var kvp in this) {
				s.AppendLine(string.Format("{0}:{1}", kvp.Key, kvp.Value));
			}
			if(s.Length>0) s.Remove(s.Length - 2, 2);
			return s.ToString();
		}
	}
}
